<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Lobby extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
    public function index()
    {
        $this->load->model("Mlobby");
        $this->Mlobby->deleteExpired();
        if($this->Mlobby->checkVisitorIsPlayer($this->session->userdata('session_id'))){
                redirect('/rooms', 'location', 302); return;
        } else
        {
            $cookie = $this->input->cookie('ci_rb_membre');
            if($cookie){
                $login = $this->Mlobby->findUserWithCookie($cookie);
            } else {
                $login = $this->session->userdata('user');
                if($login){$login = $this->Mlobby->findUserWithCookie($login);}
            }
            if($login){
                    $this->Mlobby->newPlayerAnonymous($login, $this->session->userdata('session_id'));
                    redirect('/rooms', 'location', 302); return;
            } else {
                require '/files/facebook/facebook.php';

                $facebook = new Facebook(array(
                'appId'  => '370408382994780',
                'secret' => 'd98482bf563065c3cf0ccc556c649224',
                ));

                // See if there is a user from a cookie
                $user = $facebook->getUser();
                /*
                if ($user) {
                    try {
                        // Proceed knowing you have a logged in user who's authenticated.
                        $user_profile = $facebook->api('/me');
                        $perms = $facebook->api('/me/permissions');
                    } catch (FacebookApiException $e) {
                        echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
                        $user = null;
                    }
                }*/
                if($user)
                {
                    $result = $this->Mlobby->isFacebookUserIsRegistered($user);
                    if($result)
                    {
                        $cookie = array(
                            'name'   => 'ci_rb_membre',
                            'value'  => $result["cookie"],
                            'expire' => '0'
                        );
                        $this->input->set_cookie($cookie);
                        $this->session->set_userdata('user', $result["cookie"]);
                        $this->Mlobby->newPlayerAnonymous($result["login"], $this->session->userdata('session_id'));
                        redirect('/rooms', 'location', 302); return;
                    }
                }
            }

            $this->load->view("lobby/login.php");
        }
    }
    
    private function RR(){
        $this->load->model("Mlobby");
        $this->Mlobby->RR();
    }


    public function login_finish()
    {
        if($this->input->post('login') && $this->input->post('password'))
        {
            $this->load->model("Mlobby");
            $login = $this->input->post('login');
            $password = $this->input->post('password');
            $password = $password . "rbeuqueisthebest!";
            $password = sha1($password);
                if($this->Mlobby->newPlayerRegistered($login, $password, $this->session->userdata('session_id')))
                {
                    $res = $this->Mlobby->getUserInfo($this->session->userdata('session_id'));
                    if($res){
                        $cookie = array(
                            'name'   => 'ci_rb_membre',
                            'value'  => $res["cookie"],
                            'expire' => '0'
                        );
                        $this->input->set_cookie($cookie);
                        $this->session->set_userdata('user', $res["cookie"]);
                    }
                    $this->index();
                }
                else
                {
                    $data["erreur"] = "La procédure d'identification a échouée!";
                    $this->load->view("lobby/lobby_erreur.php", $data);
                }
            /*else
            {
                if($this->Mlobby->checkAvailability($login))
                {
                    $this->Mlobby->newPlayerAnonymous($login, $perso, $this->session->userdata('session_id'));
                    redirect('/lobby', 'location', 302);
                }
                else
                {
                    $data["erreur"] = "Le pseudo choisi n'est plus disponible!";
                    $this->load->view("lobby/lobby_erreur", $data); return;
                }
            }*/
        }
        else
        {
            $data["erreur"] = "L'accès à cette page n'est pas autorisé sans passer de paramètres!";
            $this->load->view("lobby/lobby_erreur", $data); return;
        }
    }
    
    public function logout(){
        $this->load->model("Mlobby");
        $this->Mlobby->logoutUser($this->session->userdata("session_id"));
        $this->session->unset_userdata('user');
        $cookie = array(
            'name'   => 'ci_rb_membre',
            'value'  => $res["cookie"]
        );
        $this->input->set_cookie($cookie);
        redirect('/lobby', 'location', 302);
    }
    
    public function extendExpire()
    {
        $this->load->model("Mlobby");
        $result = $this->Mlobby->extendExpire($this->session->userdata('session_id'));
        $this->Mlobby->deleteExpired();
        if($result){
            $data = $result; $data["result"] = true; 
            $user = $this->Mlobby->getUserInfo($this->session->userdata("session_id"));
            if($user["isPlaying"]){
                $this->load->model("Mgame");
                $room = $this->Mgame->getRoomInfo($user["room"]);
                $data["room"] = $room;
                $data["isPlaying"] = true;
                for($i=0; $i < count($room); $i++)
                {
                    $r = $room[$i];
                    $data["player"][$i]["pseudo"] = $r["pseudo"];
                    $data["player"][$i]["hash"] = $r["hash"];
                    $data["player"][$i]["perso"] = $r["perso"];
                    $data["player"][$i]["expire"] = $r["expire"];
                }
                $this->load->view("lobby/xml_extend_game", $data);
            } else {
                $data["isPlaying"] = false;
                $this->load->view("lobby/xml_erreur", $data);
            }
        } else { 
            $data["result"] = false;
            $this->load->view("lobby/xml_erreur", $data);
        }
    }
    /*public function newUser()
    {
        if($this->input->post('login') && $this->input->post('perso'))
        {
            $this->load->model("Mlobby");
            $login = $this->input->post('login');
            $perso = $this->input->post('perso');
            if($this->input->post('password'))
            {
                $password = $this->input->post('password');
                if($this->Mlobby->newPlayerRegistered($login, $password, $perso, $this->session->userdata('session_id')))
                {
                    $this->index();
                }
                else
                {
                    $data["erreur"] = "La procédure d'identification a échouée!";
                    $this->load->view("lobby/lobby_erreur", $data); return;
                }
            }
            else
            {
                if($this->Mlobby->checkAvailability($login))
                {
                    $this->Mlobby->newPlayerAnonymous($login, $perso, $this->session->userdata('session_id'));
                    redirect('/lobby', 'location', 302);
                }
                else
                {
                    $data["erreur"] = "Le pseudo choisi n'est plus disponible!";
                    $this->load->view("lobby/lobby_erreur", $data); return;
                }
            }
        }
        else
        {
            $data["erreur"] = "L'accès à cette page n'est pas autorisé sans passer de paramètres!";
            $this->load->view("lobby/lobby_erreur", $data); return;
        }
    }*/

    public function checkAvailability($pseudo)
    {
        $this->load->model("Mlobby");
        if($this->Mlobby->checkAvailability($pseudo))
        {
            $data["result"] = 1;
        }
        else
        {
            $data["result"] = 0;
        }
        $this->load->view("lobby_checkAvailability", $data);
    }


    public function register_finish()
    {
        if ($this->input->post()) {
            $response = $this->parse_signed_request($this->input->post('signed_request'), 
                                            "d98482bf563065c3cf0ccc556c649224");
            $user = $response["registration"];
            $user["password"] = $user["password"] . "rbeuqueisthebest!";
            $user["password"] = sha1($user["password"]);
            $verif_field_rb = "[
                            {'name':'name'},
                            {'name':'pseudo',      'description':'Pseudonyme',             'type':'text'},
                            {'name':'email'},
                            {'name':'password'},
                            {'name':'gender'},
                            {'name':'birthday'}
                            ]";
            $user["inscription"] = $response["issued_at"];
            $verif_field_fb = $response["registration_metadata"]["fields"];
            if($verif_field_fb != $verif_field_rb)
            { 
                $data["erreur"] = "Ne pas modifier les champs d'inscriptions au site.";
                $this->load->view("lobby/lobby_erreur"); return;
            }
            if(array_key_exists("user_id", $response))
            {
                $user["facebook_id"] = $response["user_id"];
            } else {
                $user["facebook_id"] = null;
            }
            $this->load->model("Mlobby");
            if(!$this->Mlobby->checkAvailability($user["pseudo"]))
            {
                $data["erreur"] = "Ce pseudo n'est pas disponible.<br /><a href='/lobby/'>Retourner au formulaire d'inscription</a>";
                $this->load->view("lobby/lobby_erreur", $data);
            }
            $data["erreur"] = $this->Mlobby->registerUser($user);
            if(!$data["erreur"]){
                $this->load->view("lobby/lobby_erreur", $data);
            } else {
                if($this->Mlobby->newPlayerRegistered($user["pseudo"], $user["password"], $this->session->userdata('session_id')))
                {
                    $res = $this->Mlobby->getUserInfo($this->session->userdata('session_id'));
                    if($res){
                        $this->session->set_userdata('user', $res["cookie"]);
                        $cookie = array(
                            'name'   => 'ci_rb_membre',
                            'expire' => '0',
                            'value'  => $res["cookie"]
                        );
                        $this->input->set_cookie($cookie);
                    }
                    $this->index();
                } else {
                    $data["erreur"] = "Erreur à la connexion après register_finish"; $this->load->view("lobby/lobby_erreur", $data);
                }
            }
        } else {
            $data["erreur"] = '$_REQUEST is empty';
            $this->load->view("lobby/lobby_erreur", $data);
        }
        
    }


    private function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

  // decode the data
  $sig = $this->base64_url_decode($encoded_sig);
  $data = json_decode($this->base64_url_decode($payload), true);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

private function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
}


}

/* End of file lobby.php */
/* Location: ./application/controllers/lobby.php */